<?php
/**
 * Created by PhpStorm.
 * Users: zouyanan
 * Date: 2019/5/11
 * Time: 下午10:03
 */
namespace app\common\library\easyWechat;

use EasyWeChat\Foundation\Application;

class MiniProgram
{
    public static function application(){
        $options = [
            'mini_program' => [
                'app_id'   => '',
                'secret'   => '',
                'token'    => '',
                'aes_key'  => ''
            ]
        ];
        $app = new Application($options);
        $miniProgram = $app->mini_program;
        return $miniProgram;
    }

    /**
     * 统一下单
     */
    public function unifiedorder($order_id)
    {
        $orderInfo = db('order')->where('id', $order_id)->find();
        if (!$orderInfo) {
            return false;
        }
        $userInfo = db('user')->where('id', $orderInfo['user_id'])->find();
        if (!$orderInfo) {
            return false;
        }
        if ($orderInfo['type'] == 0) {
            $info = db('lesson')->where('id', $orderInfo['ext_id'])->find();
            if ($info) {
                $body = $info['title'];
            }
        }
        $body = isset($body)?$body:'博志成支付';
        $out_trade_no = md5($orderInfo['trade_no'] . '_' . rand(1000000, 9999999));
        db('order_log')->insertGetId([
            'order_id' => $orderInfo['id'], 
            'order_trade_no' => $out_trade_no, 
            'order_status' => 0,
            'fee' => $orderInfo['fee'],
            'createtime' => time()
        ]);
        $options = [
            'appid' => '',//小程序appid
            'mch_id' => '', //商户号
            'nonce_str' => $this->getNonceStr(),//随机字符串
            'body' => $body, //商品描述
            'out_trade_no' => $out_trade_no, //订单号
            // 'total_fee' => $orderInfo['fee'] * 100, //金额 单位 ‘分’
            'total_fee' => 1, //金额 单位 ‘分’
            'openid' => $userInfo['openid'],
			//'openid'=>'oUBZa5NOffkUF_AKtnGihFtABFLQ',
            'spbill_create_ip' => '',
            'notify_url' => 'https://'.$_SERVER['HTTP_HOST'].'/index.php/api/order/notify', //通知地址
            'trade_type' => 'JSAPI', //交易类型
        ];
        ksort($options);
        $signStr = '';
        foreach ($options as $key => $value) {
            $signStr .= $key . '=' . $value .'&';
        }
        $options['sign'] = strtoupper(md5($signStr . 'key=sdaiq83h4456782uwhsb8r8wujcdg8q9'));
        $post = $this->arrayToXml($options);
        $res = curl_request('https://api.mch.weixin.qq.com/pay/unifiedorder',$post);
        $result = $this->xmlToArray($res);
        return $result;
    }

    /**
     * 生成签名
     */
    public function getPayParam($prepay_id)
    {
        $options = [
            'appId' => 'wxfff7fc2cc2f423fb',//小程序appid
            'timeStamp' => '1267196101', //商户号
            'nonceStr' => $this->getNonceStr(),//随机字符串
            'package' => 'prepay_id='.$prepay_id,
            'signType' => 'MD5', 
        ];
        ksort($options);
        $signStr = '';
        foreach ($options as $key => $value) {
            $signStr .= $key . '=' . $value .'&';
        }
        $options['paySign'] = strtoupper(md5($signStr . 'key=sdaiq83h4456782uwhsb8r8wujcdg8q9'));
        return $options;
    }

    /**
     * 生成随机字符串
     */
    public function getNonceStr()
    {
        $str="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $key = "";
        for($i=0;$i<32;$i++)
        {
            $key .= $str{mt_rand(0,32)};
        }
        return $key;
    }

    protected function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            $xml.="<".$key.">".$val."</".$key.">";
        }
        $xml.="</xml>";
        return $xml;
    }

    //将XML转为array
    protected function xmlToArray($xml)
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;
    }
}